import 'package:common_utils/common_utils.dart';
import 'package:get/get.dart';
import 'package:psi/http/api_service.dart';
import 'package:psi/services/share_preference_service.dart';

import '../base/base_controller.dart';
import '../entity/response/login_resp.dart';
import '../routes/app_pages.dart';
import '../utils/oss_util.dart';


class UserLogic extends BaseController {

  var user = User().obs;

  bool isReview = false;

  void updateUser(User? userInfo) {
    if (userInfo == null) return;
    user.value = userInfo;
    // 保存用户信息
    SharePreferenceService.saveUser(userInfo);
    update();
  }

  void loginSuccess(LoginResp resp) {
    if (resp.data == null) {
      return;
    }
    user.value = resp.data!.user!;
    // 保存token
    SharePreferenceService.saveToken(resp.data?.token);
    // 保存用户信息
    SharePreferenceService.saveUser(resp.data?.user);
    OssUtil.instance;

    Get.offAllNamed(PageNames.home);

  }


  void logout() async {
    user.value = User();
    SharePreferenceService.removeToken();
    SharePreferenceService.removeUser();
    Get.offAllNamed(PageNames.login);
  }


  // void getUserInfo() async {
  //   try {
  //     UserInfoResp resp = await ApiService.request.getUserInfo();
  //     if (resp.code == 0 && resp.data != null) {
  //       user.value = resp.data!;
  //       updateUser(user.value);
  //     }
  //   } catch(e) {
  //     LogUtil.e(e);
  //   }
  // }


  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    if (SharePreferenceService.getUser() != null) {
      user.value = SharePreferenceService.getUser()!;
    }
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();

  }



  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }


}